﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace System
{
    /// <summary>
    /// JSON 序列化辅助
    /// </summary>
    public static class JsonHelper
    {

        /// <summary>
        /// 
        /// <para>by tangjingbo at 2010/1/7 21:21</para>
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static string ToJson(object source, Type type)
        {
            var serilializer = new DataContractJsonSerializer(type);
            using (Stream stream = new MemoryStream())
            {
                serilializer.WriteObject(stream, source);
                stream.Flush();
                stream.Position = 0;
                var reader = new StreamReader(stream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ToJson(object source)
        {
            return ToJson(source, source.GetType());
        }

        /// <summary>
        /// 
        /// <para>by tangjingbo at 2010/1/7 21:21</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str">The STR.</param>
        /// <returns></returns>
        public static T ParseJson<T>(this string str)
        {
            return (T)ParseJson(str, typeof(T));
        }

        /// <summary>
        /// 
        /// <para>by tangjingbo at 2010/1/7 21:20</para>
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <param name="objType">Type of the obj.</param>
        /// <returns></returns>
        public static object ParseJson(this string str, Type objType)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {
                var serializer = new DataContractJsonSerializer(objType);
                return serializer.ReadObject(ms);
            }
        }

        /// <summary>
        /// 通过JSON序列化深度克隆类型
        /// <para>by tangjingbo at 2010/1/7 21:20</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public static T DeepClone<T>(this T source)
        {
            string jsonString = ToJson(source);
            return jsonString.ParseJson<T>();
        }
    }
}